//
//  SFExpandableTableDemoViewController.m
//  TableViewFramework
//
//  Created by 支晓辉 on 16/3/25.
//  Copyright © 2016年 wishselfly. All rights reserved.
//

#import "SFExpandableTableDemoViewController.h"
#import "SFExpandableTableViewHeaderView.h"
#import "SFExpandableTableViewSelectedCell.h"

#define IPKEY(section, row) [NSString stringWithFormat:@"%ld,%ld", section, row]

#define ROW_HEIGHT 80.f

@interface SFExpandableTableDemoViewController ()
/** 选择了的数据 */
@property (strong, nonatomic) NSArray *allSelectedData;
/** 是否打开列表(用于已选择列表( */
@property (assign, nonatomic) BOOL isExpanded;

@end

@implementation SFExpandableTableDemoViewController
{
    CGFloat _0_0row_h;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _0_0row_h = ROW_HEIGHT;
    [self init_tableView];
    [UIApplication sharedApplication].applicationSupportsShakeToEdit = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    [self.tableView beginUpdates];
    if (_0_0row_h == ROW_HEIGHT) {
        _0_0row_h = 100.f;
    } else {
        _0_0row_h = ROW_HEIGHT;
    }
    [self.tableView endUpdates];
}

#pragma mark - Movable Table

- (void)moveRowFromIndexPath:(NSIndexPath *)srcIndexPath toIndexPath:(NSIndexPath *)destIndexPath {
    SFExpandableTableViewSectionGroup *srcGroup = self.tableData[srcIndexPath.section - 1],
    *destGroup                                  = self.tableData[destIndexPath.section - 1];
    id targetData                               = srcGroup.childData[srcIndexPath.row];
    [srcGroup.childData removeObjectAtIndex:srcIndexPath.row];
    if (destIndexPath.row >= destGroup.childData.count) {
        [destGroup.childData addObject:targetData];
    } else {
        [destGroup.childData insertObject:targetData atIndex:destIndexPath.row];
    }
    //控制已经选中的cell
    NSString *srcKey = [NSString stringWithFormat:@"%ld,%ld", srcIndexPath.section - 1, srcIndexPath.row],
             *destKey = [NSString stringWithFormat:@"%ld,%ld", destIndexPath.section - 1, destIndexPath.row];
    //是否已经确定了选中项
    BOOL isChangeSelected = NO;
    
    //当跨组移动的时候，需要对两组的已选索引进行重新编排
    if (srcIndexPath.section != destIndexPath.section) {
        NSMutableDictionary *tmpDict = self.selectedIndexPath.mutableCopy;
        if (self.selectedIndexPath[srcKey] && self.selectedIndexPath[destKey]) {
            [tmpDict removeObjectForKey:srcKey];
        } else if (self.selectedIndexPath[srcKey] && !self.selectedIndexPath[destKey]) {
            [tmpDict removeObjectForKey:srcKey];
        } else if (self.selectedIndexPath[destKey] && !self.selectedIndexPath[srcKey]) {
            [tmpDict removeObjectForKey:destKey];
        }
        for (NSInteger i = srcIndexPath.row; i < srcGroup.childData.count; i++) {
            if (i == 0)continue;
            NSString *key = IPKEY(srcIndexPath.section - 1, i);
            if (self.selectedIndexPath[key]) {
                [tmpDict removeObjectForKey:key];
                tmpDict[IPKEY(srcIndexPath.section - 1, i - 1)] = @(YES);
            }
        }
        
        for (NSInteger i = destIndexPath.row; i < destGroup.childData.count; i++) {
            NSString *key = IPKEY(destIndexPath.section - 1, i);
            NSString *prevKey = IPKEY(destIndexPath.section - 1, i - 1);
            if (self.selectedIndexPath[key]) {
                if (i > 0 && !self.selectedIndexPath[prevKey]) {
                    [tmpDict removeObjectForKey:key];
                }
                tmpDict[IPKEY(destIndexPath.section - 1, i + 1)] = @(YES);
            }
        }
        if (self.selectedIndexPath[srcKey] && self.selectedIndexPath[destKey]) {
            tmpDict[destKey] = @(YES);
            isChangeSelected = YES;
        } else {
            if (self.selectedIndexPath[srcKey] && !self.selectedIndexPath[destKey]) {
                tmpDict[destKey] = @(YES);
            }
            isChangeSelected = YES;
        }
        self.selectedIndexPath = tmpDict;
    }
    
    //如果存在交换的两项只有一项被选中的时候，交换选中索引
    if (!isChangeSelected) {
        if (self.selectedIndexPath[srcKey] && !self.selectedIndexPath[destKey]) {
            [self.selectedIndexPath removeObjectForKey:srcKey];
            self.selectedIndexPath[destKey] = @(YES);
        } else if (self.selectedIndexPath[destKey] && !self.selectedIndexPath[srcKey]) {
            [self.selectedIndexPath removeObjectForKey:destKey];
            self.selectedIndexPath[srcKey] = @(YES);
        }
    }
}

- (BOOL)canMoveIndexPathFrom:(NSIndexPath *)srcPath toIndexPath:(NSIndexPath *)destPath {
    if (destPath.section == 0 || srcPath.section == 0)return NO;
    return self.tableData[destPath.section - 1].expanded;
}

#pragma mark - Private methods

- (void)init_tableView {
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerNib:NIB(CLASS_STR([SFExpandableTableViewSelectedCell class]))
    forCellReuseIdentifier:CLASS_STR([SFExpandableTableViewSelectedCell class])];
    
    [self.tableView registerNib:NIB(CLASS_STR([SFExpandableTableViewHeaderView class]))
forHeaderFooterViewReuseIdentifier:CLASS_STR([SFExpandableTableViewHeaderView class])];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [super numberOfSectionsInTableView:tableView] + 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (section == 0) {
        return self.isExpanded ? self.selectedIndexPath.count:0;
    }
    return [super tableView:tableView numberOfRowsInSection:section - 1];
}

- (SFMovableTableViewCell *)cellFromIndexPath:(NSIndexPath *)indexPath {
    
    SFExpandableTableViewSelectedCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CLASS_STR([SFExpandableTableViewSelectedCell class])];
    
    if (indexPath.section == 0) {
        cell.title = self.allSelectedData[indexPath.row];
        cell.showHeadImageView = YES;
        cell.showSelectedButton = NO;
        cell.longPressToDrag = NO;
    } else {
        cell.title = self.tableData[indexPath.section - 1].childData[indexPath.row];
        NSString *key = [NSString stringWithFormat:@"%ld,%ld", indexPath.section - 1, indexPath.row];
        cell.checked = self.selectedIndexPath[key] != nil;
        cell.showHeadImageView = YES;
        cell.showSelectedButton = YES;
        cell.longPressToDrag = YES;
    }
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    SFExpandableTableViewHeaderView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:CLASS_STR([SFExpandableTableViewHeaderView class])];
    if (section == 0) {     //已选择
        header.title = [@"已选择" stringByAppendingFormat:@"(%ld/%ld)", self.allSelectedData.count, self.allSelectedData.count];
        header.showExpandIcon = YES;
        header.expanded = self.isExpanded;
        __weak typeof(header) wHeader = header;
        header.tapHeaderViewActionBlock = ^ {
            wHeader.expanded = self.isExpanded = !self.isExpanded;
            [tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationFade];
        };
    } else {
        SFExpandableTableViewSectionGroup *group = self.tableData[section - 1];
        header.title = [group.title stringByAppendingFormat:@"(%ld/%ld)", group.selectedCount, group.childData.count];
        header.showExpandIcon = YES;
        header.expanded = group.expanded;
        __weak typeof(header) wHeader = header;
        header.tapHeaderViewActionBlock = ^ {
            group.expanded = !group.expanded;
            wHeader.expanded = group.expanded;
            [tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationFade];
        };
    }
    return header;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 50.f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath && indexPath.section == 0 && indexPath.row == 0) {
        return _0_0row_h;
    }
    return ROW_HEIGHT;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0)return;
    NSString *key = [NSString stringWithFormat:@"%ld,%ld", indexPath.section - 1, indexPath.row];
    if (self.selectedIndexPath[key]) {
        [self.selectedIndexPath removeObjectForKey:key];
        self.tableData[indexPath.section - 1].selectedCount--;
    } else {
        self.selectedIndexPath[key] = @(YES);
        self.tableData[indexPath.section - 1].selectedCount++;
    }
    self.allSelectedData = [super selectedData];
    NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];
    [indexSet addIndex:0];
    [indexSet addIndex:indexPath.section];
    [tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationFade];
}

@end
